import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/platform/adaptive_card.dart';

/// 需求详情页面
class RequirementDetailPage extends ConsumerWidget {
  final int requirementId;

  const RequirementDetailPage({super.key, required this.requirementId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 模拟需求数据
    final requirement = {
      'id': requirementId,
      'title': '用户登录功能',
      'description': '实现用户注册、登录和权限验证功能，包括密码加密存储、会话管理、权限控制等',
      'priority': '高',
      'status': '进行中',
      'project': '电商平台优化项目',
      'assignee': '张三',
      'reporter': '产品经理',
      'createTime': '2023-05-15',
      'updateTime': '2023-05-20',
      'estimatedHours': 16.0,
      'actualHours': 8.0,
    };

    return Scaffold(
      appBar: AppBar(
        title: SelectableText('需求详情 #$requirementId'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.edit),
            onPressed: () {
              // TODO: 实现编辑功能
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: SelectableText('编辑功能开发中...')),
              );
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 基本信息卡片
            _buildBasicInfoCard(context, requirement),

            const SizedBox(height: 16),

            // 描述卡片
            _buildDescriptionCard(context, requirement),

            const SizedBox(height: 16),

            // 任务关联卡片
            _buildTasksCard(context),

            const SizedBox(height: 16),

            // 评论卡片
            _buildCommentsCard(context),
          ],
        ),
      ),
    );
  }

  Widget _buildBasicInfoCard(
      BuildContext context, Map<String, dynamic> requirement) {
    final priority = requirement['priority'] as String;
    final status = requirement['status'] as String;

    Color priorityColor;
    switch (priority) {
      case '高':
        priorityColor = Colors.red;
        break;
      case '中':
        priorityColor = Colors.orange;
        break;
      case '低':
        priorityColor = Colors.green;
        break;
      default:
        priorityColor = Colors.grey;
    }

    Color statusColor;
    switch (status) {
      case '待办':
        statusColor = Colors.grey;
        break;
      case '进行中':
        statusColor = Colors.blue;
        break;
      case '已完成':
        statusColor = Colors.green;
        break;
      case '阻塞':
        statusColor = Colors.red;
        break;
      default:
        statusColor = Colors.grey;
    }

    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: SelectableText(
                  requirement['title'] as String,
                  style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: priorityColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(16),
                  border:
                      Border.all(color: priorityColor.withValues(alpha: 0.3)),
                ),
                child: SelectableText(
                  priority,
                  style: TextStyle(
                    color: priorityColor,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Wrap(
            spacing: 16,
            runSpacing: 8,
            children: [
              _buildInfoItem(context, Icons.folder, '项目',
                  requirement['project'] as String),
              _buildInfoItem(context, Icons.person, '负责人',
                  requirement['assignee'] as String),
              _buildInfoItem(context, Icons.account_circle, '报告人',
                  requirement['reporter'] as String),
              _buildInfoItem(context, Icons.schedule, '创建时间',
                  requirement['createTime'] as String),
              _buildInfoItem(context, Icons.update, '更新时间',
                  requirement['updateTime'] as String),
              _buildInfoItem(context, Icons.timer, '预估工时',
                  '${requirement['estimatedHours']}小时'),
              _buildInfoItem(context, Icons.timer, '实际工时',
                  '${requirement['actualHours']}小时'),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: statusColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: SelectableText(
                  status,
                  style: TextStyle(
                    color: statusColor,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoItem(
      BuildContext context, IconData icon, String label, String value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 16, color: Colors.grey[600]),
        const SizedBox(width: 4),
        SelectableText(
          '$label: ',
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Colors.grey[600],
              ),
        ),
        SelectableText(
          value,
          style: Theme.of(context).textTheme.bodyMedium,
        ),
      ],
    );
  }

  Widget _buildDescriptionCard(
      BuildContext context, Map<String, dynamic> requirement) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SelectableText(
            '需求描述',
            style: Theme.of(context).textTheme.titleLarge,
          ),
          const SizedBox(height: 12),
          SelectableText(
            requirement['description'] as String,
            style: Theme.of(context).textTheme.bodyMedium,
          ),
        ],
      ),
    );
  }

  Widget _buildTasksCard(BuildContext context) {
    final tasks = [
      {'id': 1, 'title': '设计数据库表结构', 'status': '已完成', 'assignee': '李四'},
      {'id': 2, 'title': '实现用户注册接口', 'status': '进行中', 'assignee': '张三'},
      {'id': 3, 'title': '实现用户登录接口', 'status': '待办', 'assignee': '王五'},
    ];

    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SelectableText(
                '关联任务',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              TextButton(
                onPressed: () {
                  // TODO: 实现查看所有任务功能
                },
                child: const SelectableText('查看所有'),
              ),
            ],
          ),
          const SizedBox(height: 12),
          for (final task in tasks) _buildTaskItem(context, task),
        ],
      ),
    );
  }

  Widget _buildTaskItem(BuildContext context, Map<String, dynamic> task) {
    final status = task['status'] as String;

    Color statusColor;
    switch (status) {
      case '待办':
        statusColor = Colors.grey;
        break;
      case '进行中':
        statusColor = Colors.blue;
        break;
      case '已完成':
        statusColor = Colors.green;
        break;
      case '阻塞':
        statusColor = Colors.red;
        break;
      default:
        statusColor = Colors.grey;
    }

    return ListTile(
      title: SelectableText(task['title'] as String),
      subtitle: SelectableText('负责人: ${task['assignee'] as String}'),
      trailing: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: statusColor.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(12),
        ),
        child: SelectableText(
          status,
          style: TextStyle(
            color: statusColor,
            fontSize: 12,
          ),
        ),
      ),
      onTap: () {
        // TODO: 实现查看任务详情功能
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: SelectableText('查看任务详情功能开发中...')),
        );
      },
    );
  }

  Widget _buildCommentsCard(BuildContext context) {
    final comments = [
      {
        'author': '张三',
        'time': '2023-05-18 14:30',
        'content': '数据库表结构设计已完成，准备开始接口开发'
      },
      {
        'author': '李四',
        'time': '2023-05-19 09:15',
        'content': '用户注册接口开发中，预计今天完成'
      },
    ];

    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SelectableText(
                '评论',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              TextButton(
                onPressed: () {
                  // TODO: 实现添加评论功能
                },
                child: const SelectableText('添加评论'),
              ),
            ],
          ),
          const SizedBox(height: 12),
          for (final comment in comments) _buildCommentItem(context, comment),
          const SizedBox(height: 12),
          _buildCommentInput(context),
        ],
      ),
    );
  }

  Widget _buildCommentItem(BuildContext context, Map<String, dynamic> comment) {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor.withValues(alpha: 0.5),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              SelectableText(
                comment['author'] as String,
                style: Theme.of(context).textTheme.titleSmall?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
              ),
              const SizedBox(width: 8),
              SelectableText(
                comment['time'] as String,
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                      color: Colors.grey,
                    ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          SelectableText(
            comment['content'] as String,
            style: Theme.of(context).textTheme.bodyMedium,
          ),
        ],
      ),
    );
  }

  Widget _buildCommentInput(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: TextField(
            decoration: const InputDecoration(
              hintText: '添加评论...',
              border: OutlineInputBorder(),
            ),
            maxLines: 2,
          ),
        ),
        const SizedBox(width: 8),
        ElevatedButton(
          onPressed: () {
            // TODO: 实现提交评论功能
          },
          child: const SelectableText('提交'),
        ),
      ],
    );
  }
}
